package cn.jingyuan.bee.utils.text.replacer;

import cn.jingyuan.bee.utils.text.StringsBuilder;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 查找替换器，通过查找指定关键字，替换对应的值
 */
public class LookupReplacer extends StringReplacer {

    private final Map<String, String> lookupMap;

    private final Set<Character> prefixSet;

    private final int minLength;

    private final int maxLength;

    /**
     * 构造
     *
     * @param lookup 被查找的键值对
     */
    public LookupReplacer(String[]... lookup) {
        this.lookupMap = new HashMap<String, String>();
        this.prefixSet = new HashSet<Character>();

        int minLength = Integer.MAX_VALUE;
        int maxLength = 0;
        String key;
        int keySize;
        for (String[] pair : lookup) {
            key = pair[0];
            lookupMap.put(key, pair[1]);
            this.prefixSet.add(key.charAt(0));
            keySize = key.length();
            if (keySize > maxLength) {
                maxLength = keySize;
            }
            if (keySize < minLength) {
                minLength = keySize;
            }
        }
        this.maxLength = maxLength;
        this.minLength = minLength;
    }

    @Override
    protected int replace(CharSequence string, int pos, StringsBuilder out) {
        if (prefixSet.contains(string.charAt(pos))) {
            int max = this.maxLength;
            if (pos + this.maxLength > string.length()) {
                max = string.length() - pos;
            }
            CharSequence subSeq;
            String result;
            for (int i = max; i >= this.minLength; i--) {
                subSeq = string.subSequence(pos, pos + i);
                result = lookupMap.get(subSeq.toString());
                if (null != result) {
                    out.append(result);
                    return i;
                }
            }
        }
        return 0;
    }

}
